package com.qfedu.knowledge.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.qfedu.knowledge.dao.FileDao;
import com.qfedu.knowledge.entity.bo.FileInfoBO;
import com.qfedu.knowledge.entity.enums.FileTypeEnum;
import com.qfedu.knowledge.service.IFileService;
import com.qfedu.knowledge.util.RedisUtils;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @ClassName FileServiceImpl
 * @Author ykx
 * @Date 2024/5/3 11:22
 * @Version 1.0
 */
@Service
public class FileServiceImpl extends ServiceImpl<FileDao, FileInfoBO> implements IFileService {

    @Autowired
    private FastFileStorageClient storageClient;

    @Autowired
    private RedisUtils redisUtils;


    @Override
    public List<FileInfoBO> getFileList(Long questionId) {
        QueryWrapper<FileInfoBO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("question_id", questionId);
        return list(queryWrapper);
    }

    @Override
    @SneakyThrows
    public List<FileInfoBO> getHomeImage() {
        List<FileInfoBO> homeImages;
        String imgsStr = redisUtils.get("homeImages");
        if (imgsStr != null) {
            //1.redis中获取到了轮播图信息
            homeImages = JSONArray.parseArray(imgsStr, FileInfoBO.class);
        } else {
            QueryWrapper<FileInfoBO> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("type", FileTypeEnum.HOME_FILE.getCode());
            homeImages = list(queryWrapper);
            redisUtils.set("homeImages", JSON.toJSONString(homeImages));
        }
        return homeImages;
    }


    @Override
    public ResponseEntity<byte[]> download(String downloadUrl, String name) {
        StorePath storePath = StorePath.parseFromUrl(downloadUrl);
        byte[] data = storageClient.downloadFile(storePath.getGroup(), storePath.getPath(), new DownloadByteArray());
        HttpHeaders httpHeaders = new HttpHeaders();
        // 设置下载响应类型以及文件名
        httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        httpHeaders.setContentDispositionFormData("attachment", name);
        return new ResponseEntity<>(data, httpHeaders, HttpStatus.OK);
    }
}
